﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace Pentakill
{
    public partial class Suppliers : Form
    {
        SqlConnection con = new SqlConnection();
        DataGridViewRow r;
        SqlDataAdapter da;
        DataSet ds;
        SqlCommandBuilder cb;
        DataTable dt;
        DataView dv;

        public Suppliers()
        {
            InitializeComponent();

            con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

            RefreshSupplier();

        }

        void InitializeADObject_Supplier()
        {


            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "Production.Suppliers_load";

            da = new SqlDataAdapter(cmd);
            cb = new SqlCommandBuilder(da);

            ds = new DataSet();
            da.FillSchema(ds, SchemaType.Mapped);
            da.Fill(ds, "Production.Suppliers");
        }
        void LoadSupplierInfo()
        {

            dt = ds.Tables["Production.Suppliers"];
            dv = new DataView(dt);
            dgvSupplier.DataSource = dt;

        }
        void ClearForm()
        {
            txtID.Text = "";
            txtCompanyName.Text = "";
            txtContactName.Text = "";
            txtContactTitle.Text = "";
            txtAddress.Text = "";
            txtCity.Text = "";
            txtRegion.Text = "";
            mtbPostalCode.Text = "";
            cmbCountry.SelectedIndex = -1;
            mtbPhone.Text = "";
            txtFax.Text = "";
            btnUpdate.Enabled = false;
            btnDelete.Enabled = false;
            btnAdd.Enabled = true;

        }
        void RefreshSupplier()
        {
            InitializeADObject_Supplier();
            LoadSupplierInfo();
            ClearForm();
            errorProvider1.Clear();
        }

        bool validateInput()
        {
            errorProvider1.Clear();
            string name = txtCompanyName.Text;
            bool error = false;
            if (name.Trim().Length == 0)
            {
                errorProvider1.SetError(txtCompanyName, "Please enter your company name!");
                error = true;
            }

            name = txtContactName.Text;

            if (name.Trim().Length == 0)
            {
                errorProvider1.SetError(txtContactName, "Please enter your contact name!");
                error = true;
            }


            name = txtContactTitle.Text;

            if (name.Trim().Length == 0)
            {
                errorProvider1.SetError(txtContactTitle, "Please enter your contact title!");
                error = true;
            }

            name = txtAddress.Text;

            if (name.Trim().Length == 0)
            {
                errorProvider1.SetError(txtAddress, "Please enter your address!");
                error = true;
            }

            name = txtCity.Text;

            if (name.Trim().Length == 0)
            {
                errorProvider1.SetError(txtCity, "Please enter your city!");
                error = true;
            }


            if (mtbPostalCode.MaskCompleted == false && mtbPostalCode.Text.Length > 0)
            {
                errorProvider1.SetError(mtbPostalCode, "Postal Code is must 5 number");
                error = true;
            }

            if (cmbCountry.SelectedIndex == -1)
            {
                errorProvider1.SetError(cmbCountry, "Please choose a country!");
                error = true;
            }

            

            if (mtbPhone.MaskCompleted == false)
            {
                errorProvider1.SetError(mtbPhone, "Please enter required digit!");
                error = true;
            }
            if (error == true)
            {
                return false;
            }
            return true;
        }

       
        private void Suppliers_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result;
            result = MessageBox.Show("Are you want to exit?", "Exit", MessageBoxButtons.OKCancel);

            if (result == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
        }




        private void btnNew_Click(object sender, EventArgs e)
        {
            RefreshSupplier();

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (validateInput())
            {
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "Production.Suppliers_add";



                SqlParameter param = new SqlParameter("@companyname", SqlDbType.NVarChar, 40);
                param.Value = (txtCompanyName.Text);
                cmd.Parameters.Add(param);



                param = new SqlParameter("@contactname", SqlDbType.NVarChar, 30);
                param.Value = (txtContactName.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@contacttitle", SqlDbType.NVarChar, 30);
                param.Value = (txtContactTitle.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@address", SqlDbType.NVarChar, 60);
                param.Value = (txtAddress.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@city", SqlDbType.NVarChar, 15);
                param.Value = (txtCity.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@region", SqlDbType.NVarChar, 15);
                param.Value = (txtRegion.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@postalcode", SqlDbType.NVarChar, 10);
                param.Value = (mtbPostalCode.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@country", SqlDbType.NVarChar, 15);
                param.Value = (cmbCountry.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@phone", SqlDbType.NVarChar, 24);
                param.Value = (mtbPhone.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@fax", SqlDbType.NVarChar, 24);
                param.Value = (txtFax.Text);
                cmd.Parameters.Add(param);

                cmd.ExecuteNonQuery();
                con.Close();
                RefreshSupplier();

                

            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {

            if (validateInput())
            {
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "Production.Suppliers_update";
                SqlParameter param = new SqlParameter("@companyname", SqlDbType.NVarChar, 40);
                param.Value = (txtCompanyName.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@contactname", SqlDbType.NVarChar, 30);
                param.Value = (txtContactName.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@contacttitle", SqlDbType.NVarChar, 30);
                param.Value = (txtContactTitle.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@address", SqlDbType.NVarChar, 60);
                param.Value = (txtAddress.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@city", SqlDbType.NVarChar, 15);
                param.Value = (txtCity.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@region", SqlDbType.NVarChar, 15);
                param.Value = (txtRegion.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@postalcode", SqlDbType.NVarChar, 10);
                param.Value = (mtbPostalCode.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@country", SqlDbType.NVarChar, 15);
                param.Value = (cmbCountry.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@phone", SqlDbType.NVarChar, 24);
                param.Value = (mtbPhone.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@fax", SqlDbType.NVarChar, 24);
                param.Value = (txtFax.Text);
                cmd.Parameters.Add(param);

                param = new SqlParameter("@supplierid", SqlDbType.Int);
                param.Value = int.Parse(txtID.Text);
                cmd.Parameters.Add(param);

                cmd.ExecuteNonQuery();
                con.Close();


                MessageBox.Show("Update successfully!");
                RefreshSupplier();


            }
        }

        private void dgvSupplier_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvSupplier.SelectedRows.Count > 0)
            {
                btnUpdate.Enabled = true;
                btnDelete.Enabled = true;
                btnAdd.Enabled = false;
                r = dgvSupplier.SelectedRows[0];
                txtID.Text = r.Cells["supplierid"].Value.ToString();
                txtCompanyName.Text = r.Cells["companyname"].Value.ToString();
                txtContactName.Text = r.Cells["contactname"].Value.ToString();
                txtContactTitle.Text = r.Cells["contacttitle"].Value.ToString();
                txtAddress.Text = r.Cells["address"].Value.ToString();
                txtCity.Text = r.Cells["city"].Value.ToString();
                txtRegion.Text = r.Cells["region"].Value.ToString();
                mtbPostalCode.Text = r.Cells["postalcode"].Value.ToString();
                cmbCountry.Text = r.Cells["country"].Value.ToString();
                mtbPhone.Text = r.Cells["phone"].Value.ToString();
                txtFax.Text = r.Cells["fax"].Value.ToString();
                errorProvider1.Clear();

            }
        }

        void DeleteProduct()
        {
            con.Open();
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "Production.Suppliers_delete";


                SqlParameter param = new SqlParameter("@supplierid", SqlDbType.Int);

                //SqlParameter param = new SqlParameter("@supplierID", SqlDbType.Int);

                param.Value = int.Parse(txtID.Text);
                cmd.Parameters.Add(param);

                cmd.ExecuteNonQuery();
                MessageBox.Show("Delete successfully!");

            }
            catch (Exception e)
            {

                MessageBox.Show(e.Message);
            }

            con.Close();

            RefreshSupplier();
        }

        void SearchbyName()
        {
            RefreshSupplier();
            dv = new DataView(dt);
            dv.RowFilter = string.Format("companyname like '%{0}%' ", txtSearch.Text);
            dgvSupplier.DataSource = dv;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchbyName();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DeleteProduct();
        }

        void FilterbyCountry()
        {
            RefreshSupplier();
            if (cmbFilter.Text.Length != 0)
            {
                dv = new DataView(dt);
                dv.RowFilter = string.Format("Country like '{0}'", cmbFilter.Text);
                dgvSupplier.DataSource = dv;
            }

        }

        private void btnFilter_Click(object sender, EventArgs e)
        {
            FilterbyCountry();
        }

        private void txtFax_KeyPress(object sender, KeyPressEventArgs e)
        {

            // Kiểm tra xem phím nhấn có phải là số hoặc phím chức năng ko
            if (Char.IsDigit(e.KeyChar) || Char.IsControl(e.KeyChar)) { }
            // Cho phép nhập kí tự '.' để biểu diễn thập phân và chỉ cho
            // nhập kí tự '.' 1 lần

            else
            {
                e.Handled = true;
            }
        }










    }
}
